import axios from 'axios'
import router from '../router'

const URL = process.env.NODE_ENV === 'development' ? '/api' : '服务端'
axios.defaults.baseURL = URL

axios.create({
  withCredentials: true
})

// 请求拦截器
axios.interceptors.request.use(config => {
  if (config.url === '/login') {
    return config
  } else {
    const token = localStorage.getItem('token')
    config.headers.authorization = token
    return config
  }
})

// 响应拦截器
axios.interceptors.response.use(config => {
  const { data } = config
  if (data) {
    if (data.code === '1004' || data.code === '10022') {
      localStorage.removeItem('token')
      router.push({ path: '/login' })
    } else {
      return config
    }
  } else {
    alert('请求出错')
  }
})

export default axios
